﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using System.Reflection;

namespace ProgNetExtensions.LanguageExt
{
    public class LngPropertyUiEditor : UITypeEditor
    {
        IWindowsFormsEditorService srv;
        ListBox lb;
        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }
        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            srv = context.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            if (srv != null)
            {
                if (lb == null)
                {
                    lb = new ListBox();
                    lb.Click += new EventHandler(lb_Click);
                    lb.KeyDown += new KeyEventHandler(lb_KeyDown);
                    PropertyInfo[] pis = context.Instance.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
                    foreach (PropertyInfo pi in pis)
                    {
                        if (pi.CanWrite && pi.CanRead && pi.PropertyType == typeof(string))
                        {
                            if (pi.Name != "Name")
                                lb.Items.Add(pi.Name);
                        }
                    }
                }
            }
            if (value != null)
                lb.SelectedItem = value;
            srv.DropDownControl(lb);
            if (lb.SelectedItem != null)
                value = lb.SelectedItem;
            return value;
        }

        void lb_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (srv != null)
                {
                    srv.CloseDropDown();
                }
            }
        }

        void lb_Click(object sender, EventArgs e)
        {
            if (srv != null)
            {
                srv.CloseDropDown();
            }
        }
    }
}
